import Taro from '@tarojs/taro'
import { logError } from '../utils/error'
import {HTTP_STATUS} from "../constants/status";

export default {
  baseOptions(params, method = 'GET') {
    let { url, data } = params;
    let contentType = 'application/json';
    contentType = params.contentType || contentType;
    type OptionType = {
      url: string,
      data?: object | string,
      method?: any,
      header: object,
      xhrFields: object,
    }

    const option: OptionType = {
      url: url,
      data: data,
      method: method,
      header: {
        'content-type': contentType,
        'sso-sessionid': "1423199783274680321_1_1_1",
        'x-app-id': '10000'
      },
      xhrFields: { withCredentials: true },
    };

    return Taro.request(option).then(async (res)=>{
      // eslint-disable-next-line @typescript-eslint/no-shadow
      const { statusCode, data: {data} } = res;
      if (statusCode === HTTP_STATUS.NOT_FOUND) {
        return logError('api', '请求资源不存在')
      } else if (statusCode === HTTP_STATUS.BAD_GATEWAY) {
        return logError('api', '服务端出现了问题')
      } else if (statusCode === HTTP_STATUS.FORBIDDEN) {
        return logError('api', '没有权限访问')
      } else if (statusCode === HTTP_STATUS.AUTHENTICATE) {
        Taro.clearStorage();
        Taro.navigateTo({
          url: '/pages/login/index'
        });
        return logError('api', '请先登录')
      } else if (statusCode === HTTP_STATUS.SUCCESS) {
        console.log('---请求数据成功res.statusCode: ', res.statusCode, '---data:', data);
      }
      return data
    }).catch((err) => {
      const defaultMsg = err.status === HTTP_STATUS.NOT_LOGIN ? '登录失效' : '请求异常';
      Taro.showToast({
        title: err && err.errorMsg || defaultMsg,
        duration: 10,
        icon: 'none'
      });
      return Promise.reject({ message: defaultMsg, ...err })
    })
  },

  get(url, data?: object) {
    let option = { url, data };
    return this.baseOptions(option)
  },

  post: function (url, data?: object, contentType?: string) {
    let params = { url, data, contentType };
    return this.baseOptions(params, 'POST')
  },

  put(url, data?: object) {
    let option = { url, data };
    return this.baseOptions(option, 'PUT')
  },

  delete(url, data?: object) {
    let option = { url, data };
    return this.baseOptions(option, 'DELETE')
  }
}
